package com.imooc.service.impl;

import com.imooc.config.SellerConfig;
import com.imooc.config.WechatAccountConfig;
import com.imooc.dto.OrderDTO;
import com.imooc.enums.OrderStatusEnum;
import com.imooc.service.PublishMessageService;
import com.imooc.utils.EnumUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * FileName: PublishMessageServiceImpl.java
 * Description: PublishMessageServiceImpl
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2021/1/5
 */
@Service
@Slf4j
public class PublishMessageServiceImpl implements PublishMessageService {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WechatAccountConfig wechatAccountConfig;

    @Autowired
    private SellerConfig sellerConfig;

    @Override
    public void orderStatus(OrderDTO orderDTO) {
        try {
            List<WxMpTemplateData> dataList = Arrays.asList(
                    new WxMpTemplateData("first", "亲，记得收货"),
                    new WxMpTemplateData("keyword1", this.sellerConfig.getInfo().getOrDefault("name", "微信点餐")),
                    new WxMpTemplateData("keyword2", this.sellerConfig.getInfo().getOrDefault("phone", "")),
                    new WxMpTemplateData("keyword3", orderDTO.getOrderId()),
                    new WxMpTemplateData("keyword4",orderDTO.getOrderStatusEnum().getMessage()),
                    new WxMpTemplateData("keyword5", "￥" + orderDTO.getOrderAmount()),
                    new WxMpTemplateData("remark", "欢迎再次光临")
            );

            WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
            wxMpTemplateMessage.setTemplateId(wechatAccountConfig.getTemplateId().get("orderStatus"));
            wxMpTemplateMessage.setToUser(orderDTO.getBuyerOpenid());
            wxMpTemplateMessage.setData(dataList);
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            log.error("【发送订单状态变更消息】发送失败", e);
        }
    }
}
